package com.example.gymmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.gymmanagement.Utils.Result;
import com.example.gymmanagement.Utils.StatusCode;
import com.example.gymmanagement.domain.Field;
import com.example.gymmanagement.domain.Matchs;
import com.example.gymmanagement.domain.Rent;
import com.example.gymmanagement.mapper.FieldMapper;
import com.example.gymmanagement.mapper.MatchsMapper;
import com.example.gymmanagement.mapper.RentMapper;
import com.example.gymmanagement.service.MatchsService;
import com.example.gymmanagement.service.RentService;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.time.Duration;
import java.util.List;
import java.util.Objects;

/**
 * @author 蜗牛菌
 * @description 针对表【matchs】的数据库操作Service实现
 * @createDate 2023-06-08 13:46:13
 */
@Service
public class MatchsServiceImpl extends ServiceImpl<MatchsMapper, Matchs>
        implements MatchsService {
    @Autowired
    private MatchsMapper matchsMapper;
    @Autowired
    private FieldMapper fieldMapper;
    @Autowired
    private RentMapper rentMapper;
    @Autowired
    private RentService rentService;

    @Override
    public Result insert(Matchs matchs, int light) {
        boolean flag = true;
        String msg = "预约赛事成功";
        QueryWrapper<Rent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rent_field", matchs.getMatchField());
        List<Rent> rentList = rentService.list(queryWrapper);
        for (Rent rent : rentList) {
            if (rent.getRentStatus().equals("预约中")) {
                flag = false;
                break;
            }
        }
        if (flag) {
            //场地没有被租用
            System.out.println("rentList 是空的,场地没有被租用");

            double ff = 0;
            //默认场地单价
            Field field = fieldMapper.selectById(matchs.getMatchField());
            String fieldPrice = field.getFieldPrice();
            String fieldPriceLight = field.getFieldPriceLight();
            System.out.println("fieldPrice:" + fieldPrice);
            //关灯时间
            System.out.println("fieldPriceLight:" + fieldPriceLight);
            //开灯时间

            DayOfWeek dayOfWeek = matchs.getMatchStart().getDayOfWeek();
            int hour = matchs.getMatchStart().getHour();
            int minute = matchs.getMatchStart().getMinute();
            //时间判断收费，只对ff进行赋值
            if (dayOfWeek.getValue() >= 1 && dayOfWeek.getValue() <= 5) {
                //周一到周五
                if ((hour == 16 && minute >= 20)
                        || (hour == 17)
                        || (hour == 18 && minute == 0)) {
                    msg = "该时间段免费使用，" + msg;
                    //免费时间
                } else if ((hour == 8 && minute >= 30)
                        || (hour > 8 && hour < 11)
                        || (hour == 11 && minute <= 30)
                        || (hour == 14 && minute >= 30)
                        || (hour == 15)
                        || (hour == 16 && minute < 20)
                        || (hour > 18 && hour < 22)) {
                    //收费时间
                    if (light == 1) {
                        //判断是否开灯，调整收费
                        //关灯
                        try {
                            ff = Double.parseDouble(fieldPrice);
                        } catch (Exception e) {
                            System.out.println("不能将字符串转换为双精度数");
                        }
                    } else if (light == 2) {
                        //开灯
                        try {
                            ff = Double.parseDouble(fieldPriceLight);
                        } catch (Exception e) {
                            System.out.println("不能将字符串转换为双精度数");
                        }
                    } else {
                        flag = false;
                        msg = "错误开关灯代表值";
                        System.out.println("错误开关灯代表值");
                    }
                } else {
                    //不可预约时间
                    flag = false;
                    msg = "周一到周五该时间段不可被租用";
                    System.out.println("周一到周五该时间段不可被租用");
                }
            } else {
                //周六日
                if ((hour == 8 && minute >= 30)
                        || (hour > 8 && hour < 11)
                        || (hour == 11 && minute <= 30)
                        || (hour == 14 && minute >= 30)
                        || (hour > 14 && hour < 22)
                        || (hour == 22 && minute == 0)) {
                    //收费可预约时间
                    if (light == 1) {
                        //判断是否开灯，调整收费
                        try {
                            ff = Double.parseDouble(fieldPrice);
                        } catch (Exception e) {
                            System.out.println("不能将字符串转换为双精度数");
                        }
                    } else if (light == 2) {
                        try {
                            ff = Double.parseDouble(fieldPriceLight);
                        } catch (Exception e) {
                            System.out.println("不能将字符串转换为双精度数");
                        }
                    } else {
                        flag = false;
                        msg = "错误开关灯代表值";
                        System.out.println("错误开关灯代表值");
                    }
                } else {
                    //不可预约时间
                    flag = false;
                    msg = "周六日该时间段不可被租用";
                    System.out.println("周六日该时间段不可被租用");
                }
            }
            if (flag) {
                //添加赛事表数据
                try {
                    boolean success = this.matchsMapper.insert(matchs) > 0;
                    if (!success) {
                        flag = false;
                        msg = "赛事添加失败，matchsMapper.insert(matchs) < 0";
                    }
                } catch (Exception e) {
                    //success = false;
                    flag = false;
                    msg = "赛事添加失败，调用matchsMapper.insert时出错";
                }
            }
            if (flag) {
                //添加租用表数据
                Matchs match23 = matchsMapper.selectByName(matchs.getMatchName());
                long matchId = match23.getMatchId();
                //在保存好比赛后，获取比赛id

                Duration minutes = Duration.between(matchs.getMatchStart(), matchs.getMatchEnd());
                long diffOldStartEnd = minutes.toMinutes();
                int diffOldStartEnd1 = (int) diffOldStartEnd;
                //得到分钟差
                int hours = diffOldStartEnd1 / 60;
                // 计算两者之间的小时差
                ff = ff * hours;
                //获取总价

                String fieldname = field.getFieldName();

                Rent rent = new Rent();
                rent.setRentUser(matchs.getMatchOwner());
                rent.setRentStart(matchs.getMatchStart());
                rent.setRentEnd(matchs.getMatchEnd());
                rent.setRentPrice(ff);
                rent.setRentField(matchs.getMatchField());
                rent.setRentMatch(matchId);
                rent.setRentType("场地租借");
                rent.setRentDtail(matchs.getMatchName()+"(比赛)，租借" + fieldname);
                rent.setRentStatus("预约中");
                rentMapper.insert(rent);
                System.out.println("租借表添加成功");

                UpdateWrapper<Field> updateWrapper22 = new UpdateWrapper<>();
                updateWrapper22.eq("field_id", matchs.getMatchField()); // 设置 WHERE 条件
                updateWrapper22.set("field_detail", "租用中");
                fieldMapper.update(null, updateWrapper22);
            }
        } else {
            System.out.println("场地被租用");
            msg = "场地已被租用，无法预约";
            System.out.println("rentList 不是空的，场地被租用,包含 " + rentList.size() + " 个元素");
        }
        return new Result(flag ? StatusCode.SAVE_OK : StatusCode.SAVE_ERR, flag, msg);
    }

    @Override
    public Result selectList(int index, int size, Matchs matchs) {
        if (index <= 0) {
            index = 1;
        }
        if (size <= 0) {
            size = 10;
        }
        Page<Matchs> pageInfo = new Page(index, size);

        LambdaQueryWrapper<Matchs> lambdaQueryWrapper = new LambdaQueryWrapper();
        if (matchs.getMatchId() != null && matchs.getMatchId() != 0 && !Objects.equals(matchs.getMatchId(), "")) {
            lambdaQueryWrapper.eq(Matchs::getMatchId, matchs.getMatchId());
        }
        if (StringUtils.isNotEmpty(matchs.getMatchName()) && !Objects.equals(matchs.getMatchName(), "")) {
            lambdaQueryWrapper.like(Matchs::getMatchName, matchs.getMatchName());
        }
        if (matchs.getMatchField() != null && matchs.getMatchField() != 0 && !Objects.equals(matchs.getMatchField(), "")) {
            lambdaQueryWrapper.eq(Matchs::getMatchField, matchs.getMatchField());
        }
        if (matchs.getMatchOwner() != null && matchs.getMatchOwner() != 0 && !Objects.equals(matchs.getMatchOwner(), "")) {
            lambdaQueryWrapper.eq(Matchs::getMatchOwner, matchs.getMatchOwner());
        }
        if (matchs.getMatchNotice() != null && !Objects.equals(matchs.getMatchNotice(), "")) {
            lambdaQueryWrapper.eq(Matchs::getMatchNotice, matchs.getMatchNotice());
        }
        if (StringUtils.isNotEmpty(matchs.getMatchDetail()) && !Objects.equals(matchs.getMatchDetail(), "")) {
            lambdaQueryWrapper.like(Matchs::getMatchDetail, matchs.getMatchDetail());
        }


        Page<Matchs> matchsPage = matchsMapper.selectPage(pageInfo, lambdaQueryWrapper);

        System.out.println("total:" + matchsPage.getTotal());
        Integer code = matchsPage.getTotal() != 0 ? StatusCode.GET_OK : StatusCode.GET_ERR;
        String msg = matchsPage.getTotal() != 0 ? "查询成功" : "未查询到数据";
        return new Result(code, matchsPage, "查询到的数据量为：" + matchsPage.getTotal());
    }

    @Override
    public boolean updateMatch(Matchs matchs) {
        return this.matchsMapper.updateById(matchs) > 0;
    }

    @Override
    public boolean deleteById(int id) {
        Matchs matchs = matchsMapper.selectById(id);

        UpdateWrapper<Field> updateWrapper22 = new UpdateWrapper<>();
        updateWrapper22.eq("field_id", matchs.getMatchField()); // 设置 WHERE 条件
        updateWrapper22.set("field_detail", "闲置中");
        fieldMapper.update(null, updateWrapper22);

        return this.matchsMapper.deleteById(id) > 0;
    }
}




